<template>
    <div class="box">
        <header class="header">
          <van-nav-bar title="地址列表" left-arrow @click-left="$router.back()">
          </van-nav-bar>
        </header>
        <div class="content">
            <van-address-list
                v-model="chosenAddressId"
                :list="addressList"
                default-tag-text="默认"
                @add="onAdd"
                @edit="onEdit"
                @select = "updateAddress"
            />
        </div>
    </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, Cell, Button, Icon, AddressList, Toast, Dialog } from 'vant'
import { getAddressList, updateOrderAddress, deleteAddress } from '@/api/order'

Vue.use(NavBar)
Vue.use(Cell)
Vue.use(Button)
Vue.use(Icon)
Vue.use(AddressList)
Vue.use(Toast)
Vue.use(Dialog)
export default {
  data () {
    return {
      chosenAddressId: '',
      orderTime: '',
      addressList: []
    }
  },
  mounted () {
    this.getAddressList()
    this.orderTime = this.$route.query.time
  },
  methods: {
    async getAddressList () {
      var res = await getAddressList({
        userid: localStorage.getItem('userid')
      })
      if (res.data.code === '200') {
        res.data.data.map((item, index) => {
          let str = ''
          item.province === item.city
            ? str = item.province + item.county + item.addressDetail
            : str = item.province + item.city + item.county + item.addressDetail
          item.address = str
          item.id = index + 1
        })
        this.addressList = res.data.data
      }
    },
    onAdd () {
      this.$router.push({ path: 'newAddress', query: { time: this.orderTime } })
    },
    onEdit (item, index) {
      Dialog.confirm({
        message: '请开始你的选择',
        cancelButtonText: '删除 ?',
        confirmButtonText: '修改 ?'
      })
        .then(async () => {
          this.$router.push({ path: 'newAddress', query: item })
        })
        .catch(async () => {
          var res = await deleteAddress({
            addressid: item.addressid
          })
          console.log(res)
          if (res.data.code === '200') {
            this.getAddressList()
            Toast('删除地址成功')
          }
        })
    },
    async updateAddress (value) {
      Dialog.confirm({
        message: '确定选择地址吗?',
        cancelButtonText: '取消',
        confirmButtonText: '确定并且继续'
      })
        .then(async () => {
          value.time = this.orderTime
          var res = await updateOrderAddress(value)
          if (res.data.code === '200') {
            this.$router.push({ path: 'orderIndex', query: { time: this.orderTime } })
            Toast('修改订单地址成功')
          }
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="stylus" scoped>
</style>
